package yxy.game.pm2.module.yiling;

import org.joda.time.DateTimeConstants;
import org.redisson.api.RScoredSortedSet;
import org.redisson.client.protocol.ScoredEntry;
import yxy.apple.logger.Logger;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.db.newDao.YiLingInfoDao;
import yxy.game.pm2.bean.db.po.YiLingBattlePo;
import yxy.game.pm2.bean.timeline.FutureRunnable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


//夷陵之战定时任务：两小时小时计算当前战区的关卡用户情况
public class YiLingFuture extends FutureRunnable {

    protected static Logger logger = Logger.create(YiLingFuture.class);

    @Override
    public void init() {
        handle();
    }

    @Override
    public void tick() {
        handle();
    }

    @Override
    public long period() {
        return DateTimeConstants.MILLIS_PER_MINUTE * 60 * 2;// 两个钟一刷
    }

    private void handle() {
        //获取全部区信息
        try {
            Collection<AreaBean> areaBeans = AreaBean.all();
            List<YiLingBattlePo> poList = new ArrayList<>();
            for (AreaBean areaBean : areaBeans) {
                int groupId = areaBean.getGroupId();
                int areaId = areaBean.getAreaId();
                RScoredSortedSet<String> zset = RedisManager.getInstance().getConnection(RedisType.REDIS_GAME).client().getScoredSortedSet(String.format("YILING:AREAGROUP:%s:YILINGBATTLE:SORT", groupId));
                Collection<ScoredEntry<String>> entrys = zset.entryRange(0, -1);
                //每个区的玩家信息插入到数据库
                for (ScoredEntry<String> entry : entrys) {
                    String playerCode = entry.getValue();//playerCode
                    long score = entry.getScore().longValue();
                    long value = score/100;//关卡
                    PlayerBean playerBean = PlayerBean.get(playerCode);
                    //todo 插入到数据库替换玩家信息
                    YiLingBattlePo po = new YiLingBattlePo();
                    po.setPlayerCode(playerCode);
                    po.setServerId(playerBean.getServerId());
                    po.setGroupId(groupId);
                    po.setAreaId(areaId);
                    po.setMapId(Integer.parseInt(String.valueOf(value)));
                    po.setHead(playerBean.getHead());
                    po.setHeadFrame(playerBean.getHeadframe());
                    po.setUsername(playerBean.getName());
                    po.setLevel(playerBean.getLevel());
                    po.setPower(playerBean.getPower());
                    po.setUpdateTime(System.currentTimeMillis());
                    poList.add(po);
                }
            }

            //玩家的关卡变动就替换数据
            YiLingInfoDao.replace(poList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
